<template>
  <n-data-table
      :columns="columns"
      :data="rowData"
      :pagination="false"
      :loading="loading"
      :row-key="rowKey"/>

  <n-modal v-model:show="showNodeInfoModal" preset="card" @afterLeave="clearNodeInfoParam" title="手动执行"
           size="huge" :bordered="false" style="width: 700px">
    <n-space vertical>
      <n-input v-model:value="manualTriggerParam.param" size="large" type="textarea" placeholder="请输入执行参数" clearable/>
      <n-data-table
          :columns="nodeInfoColumns"
          :data="nodeInfoRowData"
          :pagination="false"
          :loading="nodeInfoLoading"
          :row-key="rowKey"/>
    </n-space>
  </n-modal>

  <n-modal v-model:show="showDependenceModal" preset="card" @afterLeave="clearDependenceParam" title="配置父任务"
           size="huge" :bordered="false" style="width: 600px">
    <n-space vertical>
      <n-select v-model:value="dependenceSchedules" :options="allSchedules" multiple filterable clearable/>
      <n-button type="primary" round size="large" block @click="handleSubmitDependence">
        <template #icon>
          <n-icon :component="CheckmarkOutline"/>
        </template>
        提交
      </n-button>
    </n-space>
  </n-modal>
</template>

<script lang="ts" setup>
import {h, reactive, onMounted, toRefs} from "vue";
import ScheduleApi from "../api/ScheduleApi";
import {JobScheduleVO, basicColumns} from "../model/Schedule";
import config from "../util/config";
import SwitchButton from "../components/table/SwitchButton.vue";
import ConfirmButton from "../components/table/ConfirmButton.vue";
import UpdateButton from "../components/table/UpdateButton.vue";
import ExecuteButton from "../components/table/ExecuteButton.vue";
import {SelectOption} from "naive-ui";
import {JobNodeVO, basicColumns as nodeBasicColumns} from "../model/Node";
import NodeApi from "../api/NodeApi";
import RunningApi from "../api/RunningApi";
import DependenceApi from "../api/DependenceApi";
import {ManualTriggerParam} from "../model/Running";
import {CheckmarkOutline} from "@vicons/ionicons5";
import {UpdateDependenceParam} from "../model/Dependence";

const props = defineProps<{
  jobMetaDataId: bigint,
  applicationName: string
}>();

const emits = defineEmits<{
  (e: "showUpdateSchedule", rowData: JobScheduleVO): void
}>();

const showUpdate = (rowData: JobScheduleVO): void => {
  emits("showUpdateSchedule", rowData);
}

const data = reactive({
  rowData: new Array<JobScheduleVO>(),
  nodeInfoRowData: new Array<JobNodeVO>(),
  nodeInfoLoading: false,
  loading: false,
  showNodeInfoModal: false,
  showDependenceModal: false,
  dependenceSchedules: new Array<string>(),
  updateDependenceParam: new UpdateDependenceParam(),
  allSchedules: new Array<SelectOption>(),
  manualTriggerParam: new ManualTriggerParam()
});


const handleQuery = (): void => {
  data.loading = true;
  ScheduleApi.queryJobSchedule(props.jobMetaDataId)
      .then(response => {
        if (response) {
          data.rowData = response;
        }
        data.loading = false;
      });
};

const handleDelete = (id: bigint): void => {
  ScheduleApi.deleteJobSchedule(id).then(() => {
    handleQuery();
  });
};

const handleChange = (id: bigint, enable: boolean): void => {
  ScheduleApi.toggleEnable(id, enable).then(() => {
    handleQuery();
  });
};

const showNodeInfo = (rowData: JobScheduleVO): void => {
  data.nodeInfoLoading = true;
  NodeApi.nodeInfo(props.applicationName)
      .then(response => {
        if (response) {
          data.nodeInfoRowData = response;
        }
        data.manualTriggerParam.jobScheduleId = rowData.id as bigint;
        data.manualTriggerParam.param = rowData.scheduleParam as string;
        data.nodeInfoLoading = false;
        data.showNodeInfoModal = true;
      });
};

const clearNodeInfoParam = (): void => {
  data.showNodeInfoModal = false;
  data.nodeInfoRowData = [];
  data.manualTriggerParam = new ManualTriggerParam();
}

const clearDependenceParam = (): void => {
  data.showDependenceModal = false;
  data.updateDependenceParam = new UpdateDependenceParam();
  data.allSchedules = [];
  data.dependenceSchedules = [];
}

const showUpdateDependence = (rowData: JobScheduleVO): void => {
  const id = rowData.id as bigint;
  data.updateDependenceParam.childScheduleId = id;
  ScheduleApi.queryAllSchedule(rowData.jobCycle as number, id.toString()).then(response => {
    const arr: SelectOption[] = [];
    response.forEach(item => {
      arr.push({label: item.jobName + "-" + item.scheduleName, value: (item.id as bigint).toString()});
    });
    data.allSchedules = arr;
    DependenceApi.queryParentIdList(id).then(res => {
      const selected: string[] = [];
      res.forEach(r => {
        selected.push(r.toString());
      });
      data.dependenceSchedules = selected;
      data.showDependenceModal = true;
    })
  });
}

const handleSubmitDependence = (): void => {
  const params: bigint[] = [];
  data.dependenceSchedules.forEach(item => {
    params.push(BigInt(item));
  });
  data.updateDependenceParam.parentScheduleIdList = params;
  DependenceApi.updateDependence(data.updateDependenceParam).then(() => {
    clearDependenceParam();
  });
}

const enableColumn = {
  title: "是否开启",
  key: "scheduleEnable",
  width: config.oneButtonColumnWidth,
  render: (rowData: JobScheduleVO) => {
    return [
      h(SwitchButton, {onHandleChange: (active: boolean): void => handleChange(rowData.id as bigint, active), active: rowData.scheduleEnable})
    ];
  }
};

const optionsColumn = {
  title: "操作",
  key: "options",
  width: 430,
  render: (rowData: JobScheduleVO) => {
    return [
      h(ConfirmButton, {onHandleEvent: () => handleDelete(rowData.id as bigint), iconType: "delete", disabled: false}),
      h(UpdateButton, {onShowUpdate: () => showUpdate(rowData)}),
      h(UpdateButton, {onShowUpdate: () => showUpdateDependence(rowData), content: "依赖配置"}),
      h(ExecuteButton, {onHandleClick: () => showNodeInfo(rowData)})
    ];
  }
};

const rowKey = (rowData: { id: bigint }) => {
  return rowData.id;
};

const columns = [...basicColumns, enableColumn, optionsColumn];

const manualTrigger = (id: bigint): void => {
  data.manualTriggerParam.nodeId = id;
  RunningApi.manualTrigger(data.manualTriggerParam).then(() => {
    clearNodeInfoParam();
  });
}

const nodeInfoOptionColumn = {
  title: "操作",
  key: "options",
  width: config.oneButtonColumnWidth,
  render: (rowData: JobNodeVO) => {
    return h(ExecuteButton, {content: "执行", onHandleClick: () => manualTrigger(rowData.id as bigint)});
  }
}

const nodeInfoColumns = [...nodeBasicColumns, nodeInfoOptionColumn];

const {
  rowData, loading, showNodeInfoModal, nodeInfoRowData, nodeInfoLoading, manualTriggerParam,
  showDependenceModal, dependenceSchedules, allSchedules
} = toRefs(data);

onMounted(() => {
  handleQuery();
});
</script>
